<?php

namespace app\admin\controller\purchase;

use app\common\model\supplier\Supplier;
use app\common\controller\Backend;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\purchase\DiffGoods;
use app\common\model\sales\CheckoutGoods;
use think\Db;
use think\Exception;

/**
 * 非经营性调整
 *
 * @icon fa fa-circle-o
 */
class Diff extends Backend
{
    
    /**
     * Diff模型对象
     * @var \app\common\model\purchase\Diff
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\purchase\Diff;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $this->handlefilter();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                    ->with(['storehouse','supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['storehouse','supplier'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','status','explain','operator','company','allfare','discount','discount_explain','actual_cost','createtime']);
                $row->visible(['storehouse']);
				$row->getRelation('storehouse')->visible(['name']);
				$row->visible(['supplier']);
				$row->getRelation('supplier')->visible(['nickname']);
            }
            $list = collection($list)->toArray();
            $status = $this->model->diff_status();
            foreach ($list as $k=>$v){
                $list[$k]['ystatus'] = $v['status'];
                $list[$k]['status'] = $status[$v['status']];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    public function add()
    {

        if ($this->request->isAjax()) {

            $params =input();
            if($params['actual_cost']>0){
                $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
                $actual_cost = $params['actual_cost'];
                if(empty($actual_cost)){
                    throw new Exception('金额异常');
                }
                $data = array(
                    'storehouse_id'=>$params['storehouse_id'],
                    'supplier_id'=>$params['supplier_id'],
                    'allfare'=>$params['allfare'],
                    'explain'=>$params['explain'],
                    'discount'=>$params['discount'],
                    'discount_explain'=>$params['discount_explain'],
                    'actual_cost'=>$params['actual_cost'],
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'company'=>$group['name'],
                    'operator'=>session('admin')['nickname'],
                );
                Db::startTrans();
                try {
                    $this->model->save($data);
                    if(!$this->model->id){
                        Db::rollback();
                        throw new Exception('添加失败');
                    }
                    Db::name('bill')->insert(array(
                        'storehouse_id'=>$params['storehouse_id'],
                        'bill_id'=>$this->model->id,
                        'type'=>4,
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'createtime'=>time(),
                    ));
                    if(isset($params['row']) && !empty($params['row'])){
                        $sdata = $params['row'];
                        $gdata = [];
                        foreach ($sdata as $k => $v) {
                            if($v['unit_price'] <= 0){
                                throw new Exception('商品价格不能为0');
                            }
                            $gdata[] = array(
                                'goods_id' => $v['goods_id'],
                                'goods_num' => $v['goods_num'],
                                'unit_price' => $v['unit_price'],
                                'ht_price' => $v['ht_price'],
                                'tax' => $v['tax'],
                                'remark' => $v['remark'],
                                'purchase_diff_id' => $this->model->id,
                                'storehouse_id' => $data['storehouse_id'],
                            );
                        }

                        $DiffGoods = new DiffGoods;
                        $DiffGoods->saveAll($gdata);
                    }
                    Db::commit();
                    return array(
                        'code'=>1,
                        'msg'=>'入库成功',
                    );
                }catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }else{
                $this->error('费用不能低于0');
            }
            exit;
//            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
//            $cdata = array(
////               'createtime'=>strtotime(input('createtime')),
//                'supplier_id'=>input('supplier_id/d',0),
//                'storehouse_id'=>input('storehouse_id/d'),
//                'explain'=>input('explain'),
//                'admin_id'=>session('admin')['id'],
//                'group_id'=>$group['group_id'],
//                'company'=>$group['name'],
//                'operator'=>session('admin')['nickname'],
//            );
        }
        $arr = explode('/',$_SERVER['REQUEST_URI']);

        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    public function seach(){
        $supplier_id = input('supplier_id/d',0);
        $storehouse_id = input('storehouse_id/d',0);

        $this->assign('supplier_id',$supplier_id);
        $this->assign('storehouse_id',$storehouse_id);
        return $this->view->fetch();
    }
    public function detail($ids){
        $row = $this->model->find($ids);
//        $DiffGoods = new DiffGoods;
        $rows = Db::name('purchase_diff_goods')
            ->field('sg.id,goods_id,goods_num,unit_price,tax,remark,title,place_origin,number,unit,specs,ht_price')
            ->alias('sg')
            ->where(array('purchase_diff_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        foreach ($rows as $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $rows[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$row['storehouse_id']);
            $rows[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);
        }


        $this->assign('rows',$rows);
        $this->assign('row',$row);
        $this->assign('ids',$ids);
        return $this->view->fetch();
    }
    public function edit($ids = null){
        $row = $this->model->find($ids);
        if ($this->request->isAjax()) {
            $actual_cost = input('actual_cost');
            if(empty($actual_cost)){
                throw new Exception('金额异常');
            }
            $data = array(
                'allfare'=>input('allfare'),
                'explain'=>input('explain'),
                'discount'=>input('discount'),
                'discount_explain'=>input('discount_explain'),
                'actual_cost'=>input('actual_cost'),
            );
            $params =input();
            Db::startTrans();
            try {
                $this->model->save($data, array('id' => $ids));

                if(isset($params['row']) && !empty($params['row'])){
                    $sdata = $params['row'];
                    $gdata = [];
                    foreach ($sdata as $k => $v) {
                        if($v['unit_price'] <= 0){
                            throw new Exception('商品价格不能为0');
                        }
                        $gdata[] = array(
                            'id' => $v['id'],
                            'goods_num' => $v['goods_num'],
                            'unit_price' => $v['unit_price'],
                            'ht_price' => $v['ht_price'],
                            'tax' => $v['tax'],
                            'remark' => $v['remark'],
                        );

                    }
                    $DiffGoods = new DiffGoods;
                    $DiffGoods->saveAll($gdata);
                }
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'修改成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        $rows = Db::name('purchase_diff_goods')
            ->field('sg.id,goods_id,goods_num,unit_price,ht_price,tax,remark,title,place_origin,number,unit,specs')
            ->alias('sg')
            ->where(array('purchase_diff_id'=>$ids))
            ->join('goods g','sg.goods_id = g.id')
            ->select();
        foreach ($rows as $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $rows[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$row['storehouse_id']);
            $rows[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$row['storehouse_id']);
        }

        $arr = explode('/',$_SERVER['REQUEST_URI']);

        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        $this->assign('rows',$rows);
        $this->assign('row',$row);
        $this->assign('ids',$ids);
        return $this->view->fetch();
    }
    public function examine($ids){
        $row = $this->model->find($ids);
        if(empty($row)){
            $this->error('异常');
        }
        $status = input('status/d',0);
        if ($status == 1){
            $data = array(
                'allfare'=>input('allfare'),
                'explain'=>input('explain'),
                'discount'=>input('discount'),
                'discount_explain'=>input('discount_explain'),
                'actual_cost'=>input('actual_cost'),
                'status'=>2,
            );
            $params =input();
            Db::startTrans();
            try {
                $this->model->save($data, array('id' => $ids));

                $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

                if(isset($params['row']) && !empty($params['row'])){
                    $sdata = $params['row'];

                    $gdata = [];
                    foreach ($sdata as $k => $v) {
                        if($v['unit_price'] <= 0){
                            throw new Exception('商品价格不能为0');
                        }
                        $gdata[] = array(
                            'id' => $v['id'],
                            'goods_num' => $v['goods_num'],
                            'unit_price' => $v['unit_price'],
                            'ht_price' => $v['ht_price'],
                            'tax' => $v['tax'],
                        );

                        $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                        if($hgood['stock'] == 0){
                            throw new Exception('库存为0');
                        }


                        if($hgood['stock'] == $v['goods_num']){
                            $balance = 0;
                        }else{
                            $balance = $hgood['balance']-handle_price($v['ht_price'],$v['tax'])*$v['goods_num'];
                        }


                        Db::name('goods_stock_log')->insert(array(
                            'goods_id'=>$v['goods_id'],
                            'createtime'=>time(),
                            'number'=>isset($row['number'])?$row['number']:'',
                            'type'=>'非经营性调整',
                            'source'=>4,
                            'type_id'=>$row['id'],
//                       'enter_num'=>$v['goods_num'],
                            'out_num'=>$v['goods_num'],
                            'before_num'=>$hgood['stock'],
                            'now_num'=>$hgood['stock']-$v['goods_num'],
                            'storehouse_id'=>$row['storehouse_id'],
//                       'remark'=>$v['goods_id'],
                            'controller'=>'purchase/diff',
                            'admin_id'=>session('admin')['id'],
                            'group_id'=>$group['group_id'],
                            'company'=>$group['name'],
                            'operator'=>session('admin')['nickname'],
                            'final_cost'=>handle_price($v['ht_price'],$v['tax']), //记录的金额应该是入库的加权单价
//                            'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                            'bill_cost'=>handle_price($v['ht_price'],$v['tax'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                            'balance'=>$balance, //记录的金额当前库存总额
                        ));

                        //减少库存
                        $GoodsHouseStock = new GoodsHouseStock;
                        $res = $GoodsHouseStock->reducestock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],handle_price($v['ht_price'],$v['tax']));
                        if(!$res){
                            throw new Exception('库存异常');
                        }
                    }
                    $DiffGoods = new DiffGoods;
                    $DiffGoods->saveAll($gdata);
                }

                $custrow = Supplier::find($row['supplier_id']);
                //产生一笔费用
                $ress = Db::name('analysis')->insert(array(
                    'is_income' => 2,
                    'source' => 4,
                    'cost' => -$data['actual_cost'],
//                    'admin_id' => session('admin')['id'],
//                    'group_id' => $group['group_id'],
//                    'company' => $group['name'],
                    'admin_id'=>$row['admin_id'],
                    'group_id'=>$row['group_id'],
                    'company'=>$row['company'],
                    'operator'=>$row['operator'],

                    'source_id' => $row['id'],
                    'obj_id' => $row['supplier_id'],
//                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/diff',
                    'settle_name' => $custrow['nickname'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                    'storehouse_id' => $row['storehouse_id'],
                    'explain'=>$row['explain'],//摘要
                ));
                if (!$ress) {
                    throw new Exception('数据异常');
                }

                $type = 1;
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'purchase/diff',
                    'source_id'=>$ids,
                    'source'=>4,
                    'remark'=>'非经营性调整',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'审核成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        //驳回
        if($status == 3){
            $res = $this->model->save(array('status'=>3),array('id'=>$ids));
            if($res){
                $type = 2;
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'purchase/diff',
                    'source_id'=>$ids,
                    'source'=>4,
                    'remark'=>'非经营性调整',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));
                $this->success('驳回成功');
            }else{
                $this->success('驳回失败');
            }

        }
    }
    public function cancelbill($ids = null){
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        if(!$this->request->isAjax()){
            $this->error('非法操作');
        }
        $row = $this->model->find($ids);
        if($row['status'] !=2){
            $this->error('状态异常');
        }
        $analysis = Db::name('analysis')->where(array(
            'source'=>4,
            'source_id' => $row['id'],
            'storehouse_id' => $row['storehouse_id'],
        ))->find();
        //只有财务数据在待处理的时候 才能处理
        if($analysis['status'] != 1){
            $this->error('财务状态异常,请处理');
        }
        Db::startTrans();
        try {

            //中止本单据
            $this->model->save(array('status'=>4), array('id' => $ids));
            //所有商品状态设置0
            $DiffGoods = new DiffGoods;
            $DiffGoods->save(array('status'=>0),array('purchase_diff_id'=>$ids));

            $diffgoods = new DiffGoods();
            $list = $diffgoods->where(array('purchase_diff_id'=>$ids))->select();

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

            foreach ($list as $k => $v) {
                //增加库存
                $GoodsHouseStock = new GoodsHouseStock;
                $res = $GoodsHouseStock->addstock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],handle_price($v['ht_price'],$v['tax']),1);
                if(!$res){
                    throw new Exception('库存异常');
                }

                $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();

                Db::name('goods_stock_log')->insert(array(
                    'goods_id'=>$v['goods_id'],
                    'createtime'=>time(),
                    'number'=>isset($row['number'])?$row['number']:'',
                    'type'=>'非经营性调整',
                    'source'=>4,
                    'type_id'=>$row['id'],
                    'enter_num'=>$v['goods_num'],
//                    'out_num'=>$v['goods_num'],
                    'before_num'=>$hgood['stock']-$v['goods_num'],
                    'now_num'=>$hgood['stock'],
                    'storehouse_id'=>$row['storehouse_id'],
                    'controller'=>'purchase/diff',
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'company'=>$group['name'],
                    'operator'=>session('admin')['nickname'],
                    'final_cost'=>handle_price($v['ht_price'],$v['tax']), //记录的金额应该是入库的加权单价
                    'bill_cost'=>handle_price($v['ht_price'],$v['tax'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                    'balance'=>$hgood['balance'], //记录的金额当前库存总额
                    'is_cancel'=>1,
                ));
            }
            //中止财务记录
            $ress = Db::name('analysis')->where(array(
                'id' => $analysis['id']
            ))->update(array('status' => 4));
            if (!$ress) {
                throw new Exception('数据异常');
            }
            //添加中止记录
            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 4,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/diff',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));



            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'purchase/diff',
                'source_id'=>$ids,
                'source'=>4,
                'remark'=>'非经营性调整',
                'number'=>isset($row['number'])?$row['number']:'',
            ));
            Db::commit();
            return array(
                'code'=>1,
                'msg'=>'成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

    }
}
